package com.wdc.patterns.factory.config_factoory;

import java.io.IOException;
import java.io.InputStream;
import java.security.Key;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Properties;

public class CoffeeFactory {

    //加载配置文件，获取配置文件中配置的全类名，并创建该类的对象进行存储
    //1. 定义容器对象存储coffee对象
    private static HashMap<String, Coffee> map = new HashMap<>();

    //2.加载配置文件
    static {
        Properties properties = new Properties();
        InputStream is = CoffeeFactory.class.getClassLoader().getResourceAsStream("bean.properties");
        try {
            properties.load(is);

            Iterator<Object> iterator = properties.keySet().iterator();
            while (iterator.hasNext()) {
                String key = (String) iterator.next();
                String className = properties.getProperty(key);
                //通过反射技术创建对象
                Class aClass = Class.forName(className);
                Coffee coffee = (Coffee) aClass.newInstance();
                //存储对象
                map.put(key, coffee);

            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static Coffee creteCoffee(String name) {
        return map.get(name);
    }

}
